var insertedRows = new Array();
var updatedRows = new Array();
var removedRows = new Array();
var insertCounter = 0;
var currentPage;

function saveSpecies(obj, method){

    var isValid = validate(obj);

    if (!isValid) {
        return false;
    }

    if (method == 'add') {
        obj.dirtyid = insertCounter;

        // add new html row into species list table, and into collection
        $("#species-list").append(constructLine(obj));

        // when a row is clicked, forward it to edit mode
        $("#species-list-body tr").click(function(){
            var id = $(this).attr('id').replace('sp', '');
            editForm(id); // implemented in _speciesForm
        });

        insertedRows.push(obj);

        // set cancel-add handler
        $("#cancel_" + obj.dirtyid).click(function(){
            cancel($(this));
        });

        clearForm();

        insertCounter++;

    } else if (method == 'edit') {

        var found = 0;
        for (i=0; i<updatedRows.length; i++){
            if (updatedRows[i].id == obj.id){
                updatedRows[i] = obj;
                found = 1;
                break;
            }
        }

        if (!found)
            updatedRows.push(obj);

        // update table values
        $('#odd_name_'+obj.id).html(obj.speciesname);
        $('#odd_qt_'+obj.id).html(obj.quantity);
        $('#odd_unit_'+obj.id).html(obj.unit);
        $('#odd_tags_'+obj.id).html(obj.tags);

        // changed row coloring
        $('#odd_name_'+obj.id)
        .add($('#odd_qt_'+obj.id))
        .add($('#odd_tags_'+obj.id))
        .add($('#odd_unit_'+obj.id))
        .css({'font-style': 'italic', 'color' : 'red'});

    } else if (method == 'remove') {
        removedRows.push(obj);

        // give mark as strikethrough text
        $('#odd_name_'+obj.id).html('<del>'+ $('#odd_name_'+obj.id).html() + '</del>');
        $('#odd_qt_'+obj.id).html('<del>' + $('#odd_qt_'+obj.id).html() + '</del>');
        $('#odd_tags_'+obj.id).html('<del>' + $('#odd_tags_'+obj.id).html() + '</del>');

        // and italic red text
        $('#odd_name_'+obj.id)
        .add($('#odd_qt_'+obj.id))
        .add($('#odd_tags_'+obj.id))
        .css({'font-style': 'italic', 'color' : 'red'});

    }
    else {
        alert('Error: Unknown method.');
    }

    return true;
}

function cancel(elem){
//        alert('ok');
    var dirtyid = elem.attr("id").replace("cancel_", "");
    for(i=0; i<insertedRows.length; i++) {
        if (insertedRows[i].dirtyid == dirtyid) {
            insertedRows.splice(i, 1);
            break
        }
    }
    $("#sp"+dirtyid).remove();
}

function validate(fields){
    $('#validate-tip').text("");
    $('#validate-tip').removeClass("ui-state-error");
    $('#validate-tip').show();

    if (depth.val() == "") {
        $('#validate-tip').text("Depth value must not be empty.");
        $('#validate-tip').addClass("ui-state-error");
        depth.addClass("ui-state-error");
        return false;
    }

    if (speciesname.val() == "") {
        $('#validate-tip').text("Species name must not be empty.");
        $('#validate-tip').addClass("ui-state-error");
        speciesname.addClass("ui-state-error");
        return false;
    }

    if (quantity.val() == "") {
        $('#validate-tip').text("Quantity value required.");
        $('#validate-tip').addClass("ui-state-error");
        quantity.addClass("ui-state-error");
        return false;
    }

    if (speciesid.val() == "") {
        $('#validate-tip').text("Unknown species: " + speciesname.val());
        $('#validate-tip').addClass("ui-state-error");
        speciesname.addClass("ui-state-error");
        return false;
    }

    $('#validate-tip').hide();
    return true;
}

function constructLine(obj) {
    return "<tr id='sp"+ obj.dirtyid +"'>" +
        "<td id='odd_name_'"+ obj.dirtyid +">" + obj.speciesname + "</td>" +
        "<td id='odd_qt_'"+ obj.dirtyid +">" + obj.quantity + "</td>" +
        "<td id='odd_unit_'"+ obj.dirtyid +">" + obj.unit + "</td>" +
        "<td id='odd_tags_'"+ obj.dirtyid + ">" + obj.tags + "</td>" +
        "<td><span class='dirty-obs'>new</span><span class='link-div' id='cancel_"+ obj.dirtyid +"'>cancel</span></td>"
        "</tr>";
}

function saveChanges(){

    if (insertedRows.length == 0 && updatedRows == 0 && removedRows == 0) {
        alert('No changes.');
        return false;
    }

    // if new depth, then dont use ajax. and it must be insert action only
    if ('new' == getParamValue(window.location.href, "depth")) {
        window.location = "/data/updateSpecies" +
            "/obs/" + getParamValue(window.location.href, "obs") +
            "/inserts/" + JSON.stringify(insertedRows);

    } else {
        $.ajax({
           type: 'post',
           data: {
               inserts: JSON.stringify(insertedRows),
               updates: JSON.stringify(updatedRows),
               removes: JSON.stringify(removedRows),
               page: currentPage,
               depth: getParamValue(window.location.href, "depth")
           },
           url: "/data/updateSpecies",
           dataType: 'html',
           success: function(data, textStatus, jqXHR) {
                $("#table-wrap").html(data);
                return false;
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert("error: " + textStatus + ", " + errorThrown);
                return false;
            }
        });
    }

    // reset
    insertedRows = new Array();
    updatedRows = new Array();
    removedRows = new Array();
    insertCounter = 0;

    // clear form
    allfields.val( "" ).removeClass( "ui-state-error" );
    unit.clearOptions();
    toggleButton('add');

    return true;
}

function readPage(page){
    var depth = getParamValue(window.location.href, "depth");
    currentPage = page;
//        alert(page);

    $.ajax({
       type: 'post',
       url: "/data/species",
       data: {depth: depth, page: page},
       dataType: "html",
       success: function(data, textStatus, jqXHR) {
            $("#table-wrap").html(data);
            return false;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("error: " + textStatus + ", " + errorThrown);
            return false;
        }
    });
}

function rowHover(selector) {
    if (selector == "")
        selector = "#species-list-body tr";

    $(selector).hover(
        function(){
            $(this).css('cursor', 'pointer')
        },
        function(){
            $(this).css('cursor', 'default')
        }
    );

    // when a row is clicked, forward it to edit mode
    $(selector).click(function(){
        var id = $(this).attr('id').replace('sp', '');
        editForm(id); // implemented in _speciesForm
    });
}

function remove(element) {
    var id = element.attr("id").replace('odd_remove_', '');

    if (element.button('option', 'label') == "Remove") {
        element.button('option', 'label', "Undo");

        // set row color to gray
        $('td[id*="'+id+'"]').each(function(){
            $(this).css('color', '#BBBBBB');
            $(this).children().each(function(){
                $(this).css('color', '#BBBBBB');
            });
        })

        removedRows.push(id);
    } else {
        element.button('option', 'label', "Remove");
        for(i=0; i<removedRows.length; i++) {
            if (removedRows[i] == id) {
                removedRows.splice(i, 1);
                break;
            }
        }

        // reset row color
        $('td[id*="'+id+'"]').each(function(){
            $(this).css('color', '');
            $(this).children().each(function(){
                $(this).css('color', '');
            });
        })
    }

}


